package com.cn.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.UserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import com.cn.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/back/user/findAll")
public class UserFindAllServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //1.接收数据
        String username = req.getParameter("username");
        String hobby = req.getParameter("hobby");
        String start = req.getParameter("start");
        String end = req.getParameter("end");

        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String enable = req.getParameter("enable");
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");


//        根据拿到的数据去数据库查询是否有当前的用户名和密码
//        首先需要判断验证码是否输入正确,是属于逻辑关系，
//        所以一般情况会传入到service层去做
//        2.封装数据
        UserModel userModel = new UserModel();
        userModel.setUsername(Tool.nullToString(username));
        userModel.setStart(Tool.nullToString(start));
        userModel.setEnd(Tool.nullToString(end));
        userModel.setPhone(Tool.nullToString(phone));
        userModel.setSex(Tool.nullToString(sex));
        userModel.setHobby(Tool.nullToString(hobby));
        userModel.setEnable(Tool.enableToInt(enable));
        userModel.setPage(Tool.pageToInt(page));
        userModel.setLimit(Tool.limitToInt(limit));
//        3.调用逻辑层
        UserService userService = new UserServiceImpl();
//        4.得到返回数据
        List<UserModel> result = userService.findAll(userModel);
//所以我们需要将结果封装成json格式的对象
// 5.返回数据到页面
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", result);
        resp.getWriter().println(jsonObject);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
